﻿using UnityEngine;
using System.Collections;
using VFramework;


namespace VFramework{
	/***
	 * 系统管理包括不限 
	 * 音效
	 * 音乐
	 * 灯光开光
	 * **/
	public class SystemMgr :MonoBehaviour,ISingleton {

		private AudioSource[] audioSources;

		private SystemMgr(){}

		public static SystemMgr getInstance(){
			return Singleton<SystemMgr>.getInstance ();
		}

		public void init(){
			VLogger.info ("SystemMgr:init----------");
		}
		public void initEvent(){
			VLogger.info ("SystemMgr:initEvent----------");
			EventMgr.getInstance ().addEvent (FrameEvents.MUSIC_SLIDE_VALUE_CHANGE, delegate(EventData data) {
				float v = (float)data.data;
				PlayerPrefs.SetFloat(FrameEvents.MUSIC_SLIDE_VALUE_CHANGE,v);
				setMusicV(v);
				return null;
			});

			EventMgr.getInstance ().addEvent (FrameEvents.EFFECT_SLIDE_VALUE_CHANGE, delegate(EventData data) {
				float v = (float)data.data;
				PlayerPrefs.SetFloat(FrameEvents.EFFECT_SLIDE_VALUE_CHANGE,v);
				setEffectV(v);
				return null;
			});

			EventMgr.getInstance ().addEvent (FrameEvents.LIGHT_TOGGLE_VALUE_CHANGE, delegate(EventData data) {
				bool v = (bool)data.data;
				PlayerPrefs.SetInt(FrameEvents.LIGHT_TOGGLE_VALUE_CHANGE,v?1:0);
				return null;
			});
		}

		public void release(){
			this.audioSources = null;
		}


		public void setMusicV(float v){
			this.audioSources [0].volume = 0;
		}

		public void setEffectV(float v){
			for (int i = 1; i < VConfig.MAX_AUDIO_SOURCE; i++) {
				this.audioSources [i].volume = v;
			}
		}
		 

		public void initAudio(Camera cam){
			for (int i = 0; i < VConfig.MAX_AUDIO_SOURCE; i++) {
				cam.gameObject.AddComponent<AudioSource> ();
			}

			audioSources = new AudioSource[VConfig.MAX_AUDIO_SOURCE];
			AudioSource[] tmp = cam.GetComponents<AudioSource> ();
			for (int i = 0; i < this.audioSources.Length && i < tmp.Length; i++) {
				audioSources [i] = tmp [i];
			}
		}

		public AudioSource getEffectAudioSource ()
		{
			for (int i = 1; i < audioSources.Length - 1; i++) {
				AudioSource audio = audioSources [i];
				if (!audio.isPlaying) {
					return audio;
				}
			}
			return null;
		}

		/**
		 * 第0个给背景音乐固定用
		 * 
		**/
		public AudioSource getMusicAudioSource(){
			return this.audioSources [0];
		}

		public AudioSource getAudioSourceByIndex(int index){
			if (index < VConfig.MAX_AUDIO_SOURCE && index > 0 ) {
				return this.audioSources [index];
			}
			return null;
		}






		public float getMusicValue(){
			return PlayerPrefs.GetFloat (FrameEvents.MUSIC_SLIDE_VALUE_CHANGE, 1.0f);
		}

		public float getEffectValue(){
			return PlayerPrefs.GetFloat (FrameEvents.EFFECT_SLIDE_VALUE_CHANGE, 1.0f);
		}

		public int getLightValue(){
			return PlayerPrefs.GetInt (FrameEvents.LIGHT_TOGGLE_VALUE_CHANGE, 1);
		}
	}
}